#include <stdio.h>
#include <sys/types.h>
#include <pthread.h>
#include <semaphore.h>
#include <stdlib.h>
#include <time.h>

#include <unistd.h>

#define KEY 0x8f

sem_t sem1,sem2,sem3; 
int x; // 全局变量

void *task1(void *arg){
    for(int i=0;i<5; i++){
        sem_wait(&sem1);
        x = rand()% 91+10;
        sem_post(&sem2);
    }
    return NULL;
}
void *task2(void *arg){
    while(1){
        sem_wait(&sem2);
        x ^= KEY;
        sleep(1);
        sem_post(&sem3);
    }
    return NULL;
}
void *task3(void *arg){
    while(1){
        sem_wait(&sem3);
        printf("随机产生的数值(%d)-->%d\n", x ^ KEY , x);
        sem_post(&sem1);
    }
    return NULL;
}

int main(){
   srand(time(NULL));
   sem_init(&sem1, 0, 1);
   sem_init(&sem2, 0, 0);
   sem_init(&sem3, 0, 0);
   pthread_t tid1,tid2, tid3;
   pthread_create(&tid1, NULL, task1, NULL);
   pthread_create(&tid2, NULL, task2, NULL);
   pthread_create(&tid3, NULL, task3, NULL);
   
   pthread_join(tid1, NULL);
   sleep(2);
   pthread_cancel(tid2);
   pthread_cancel(tid3);
   sem_destroy(&sem1);
   sem_destroy(&sem2);
   sem_destroy(&sem3);
   return 0;
}